<script setup lang="ts">
import { reactive, ref, toRefs, watchEffect } from "vue";
import dayjs from "dayjs";
import type { Dayjs } from "dayjs";
import {
  IAsyncDict,
  IDictSelect,
  ISearch,
  ITypeState,
  RangeValue,
  selectObjInit,
} from "@/components/global/TableSearch/types.ts";
import { fetchDictOpts } from "@/api/common";
import { ISearchParams, ISelectObj } from "@/utils/types/key-value-any.ts";

const props = defineProps<{
  searchList: Array<ISearch>;
}>();
const emit = defineEmits(["setTableParams"]);
const { searchList } = toRefs(props);
const state = reactive<ITypeState>({
  selectObj: selectObjInit,
  selectList: [],
  selectValue: "",
  inputVal: "",
  selectStatusVal: "",
  showTimes: {
    format: "HH:mm:ss",
    defaultValue: [
      dayjs("00:00:00", "HH:mm:ss"),
      dayjs("23:59:59", "HH:mm:ss"),
    ],
  },
});
const datatimes = ref<RangeValue | null>();
watchEffect(() => {
  state.selectValue = searchList.value.length ? searchList.value[0].value : "";
  state.selectObj = searchList.value.length
    ? searchList.value[0]
    : selectObjInit;
});
const getTabelData = (datas: ISelectObj[]) => {
  // 处理数据给table-params
  const params: ISearchParams = {};
  datas.forEach((item: ISelectObj) => {
    if (item.type === "timeRange" || item.type === "monthRange") {
      const timearr = item[item.value].split("~");
      if (item.value === "create") {
        params.startTime = timearr[0];
        params.endTime = timearr[1];
      } else {
        params[`start${item.value}Time`] = timearr[0];
        params[`end${item.value}Time`] = timearr[1];
      }
    } else {
      params[item.value] = item[item.value];
    }
  });
  // params tabel参数
  // console.log("查询table的参数：", params);
  emit("setTableParams", params);
};
const statusOpt = ref([]);
// 塞给selectList
const setSelectListData = () => {
  const { selectList, selectObj } = state;
  if (!selectList.length) {
    selectList.push(selectObj);
  } else {
    const aaa = selectList.filter(
      (item: ISelectObj) => item.value === selectObj.value,
    );
    if (!aaa.length) {
      selectList.push(selectObj);
    }
  }
  state.selectList = selectList;
  getTabelData(selectList);
};
// 自动识别下拉框选择
const onSelectChange1 = (val: string) => {
  state.selectObj = searchList.value.filter(
    (item: ISearch) => item.value === val,
  )[0];
  state.inputVal = "";
  state.selectStatusVal = "";
  datatimes.value = null;
  state.selectValue = val;
  // selectDict 字典查询，设置statusOpt
  state.selectObj.selectDict &&
    fetchDictOpts(state.selectObj.selectDict).then(res => {
      statusOpt.value = res.data.map((item: IAsyncDict) => ({
        label: item.message,
        value: item.name,
      }));
    });
};
const onSelectChange2 = (_e: number, data: IDictSelect) => {
  const { value, label } = data;
  state.selectObj[state.selectObj.value] = value;
  state.selectObj[`${state.selectObj.value}name`] = label;
  setSelectListData();
};
// 时间查询
const onTimeok = (dates: [Dayjs, Dayjs]) => {
  const stime = dayjs(dates[0]).format("YYYY-MM-DD HH:mm:ss");
  const etime = dayjs(dates[1]).format("YYYY-MM-DD HH:mm:ss");
  state.selectObj[state.selectObj.value] = `${stime}~${etime}`;
  setSelectListData();
};
// n年月查询
const onMonthok = (dates: [Dayjs, Dayjs]) => {
  const stime = dayjs(dates[0]).format("YYYY-MM");
  const etime = dayjs(dates[1]).format("YYYY-MM");
  state.selectObj[state.selectObj.value] = `${stime}~${etime}`;
  setSelectListData();
};
// 搜索icon点击
const searchHandle = () => {
  if (!state.inputVal) {
    return;
  }
  state.selectObj[state.selectObj.value] = state.inputVal;
  state.inputVal = "";
  setSelectListData();
};

const resetSearch = () => {
  state.selectObj = selectObjInit;
  state.selectList = [];
  state.inputVal = "";
  state.selectStatusVal = "";
  datatimes.value = null;
  state.selectValue = "";
  getTabelData(state.selectList);
};

const removeSelect = (idx: number) => {
  state.selectList.splice(idx, 1);
  if (!state.selectList.length) {
    resetSearch();
    return;
  }
  getTabelData(state.selectList);
};
</script>

<template>
  <a-card :title="null" :bordered="false">
    <div style="display: flex">
      <div style="display: flex; margin-right: 12px; border: 1px solid #d9d9d9">
        <a-select
          :value="state.selectValue"
          class="select-bg"
          :bordered="false"
          placeholder="搜索选择"
          :options="searchList"
          @change="onSelectChange1"
        >
          <template #suffixIcon>
            <JIcon
              type="icon-ic_search_arrow"
              style="margin-top: -2px; font-size: 12px; color: #000"
            />
          </template>
        </a-select>
        <a-select
          v-if="state.selectObj.type && state.selectObj.type === 'select'"
          :value="state.selectStatusVal"
          labelInValue
          :bordered="false"
          placeholder="请选择"
          style="width: 400px; margin-top: 3px"
          :options="statusOpt"
          @change="onSelectChange2"
        ></a-select>
        <LoadSelect
          v-else-if="
            state.selectObj.type && state.selectObj.type == 'loadSelect'
          "
          style="width: 400px; margin-top: 3px"
          :bordered="false"
          v-model:value="state.selectStatusVal"
          @change="onSelectChange2"
          :url="state.selectObj.selectUrl"
          :handle="state.selectObj.handle"
        />
        <a-range-picker
          v-else-if="
            state.selectObj.type && state.selectObj.type === 'timeRange'
          "
          style="width: 400px; margin-top: 0"
          class="jutime-picker"
          :show-time="state.showTimes"
          format="YYYY-MM-DD HH:mm:ss"
          :placeholder="['开始时间', '结束时间']"
          @ok="onTimeok"
          v-model:value="datatimes"
        />
        <a-range-picker
          v-else-if="
            state.selectObj.type && state.selectObj.type === 'monthRange'
          "
          style="width: 400px; margin-top: 0"
          class="jutime-picker"
          format="YYYY-MM"
          picker="month"
          :placeholder="['开始月份', '结束月份']"
          @change="onMonthok"
          v-model:value="datatimes"
        />
        <a-input
          v-else
          v-model:value="state.inputVal"
          :disabled="!state.selectObj.value"
          placeholder="请输入搜索内容"
          style="width: 400px; margin-top: 0"
        />
        <div class="jsearch-icon">
          <a-button type="text" @click="searchHandle">
            <template #icon><JIcon type="icon-ic_search" /></template>
          </a-button>
        </div>
      </div>
      <a-button size="large" @click="resetSearch">重置</a-button>
    </div>
    <div class="jsearch-selects">
      <div
        class="select-item"
        v-for="(item, index) in state.selectList"
        :key="index"
      >
        <span>{{ item.label }}</span>
        <span>
          {{
            item.type == "select" || item.type == "loadSelect"
              ? item[`${item.value}name`]
              : item[item.value]
          }}
        </span>
        <JIcon
          type="icon-ic_search_tag_close"
          style="font-size: 14px; cursor: pointer"
          @click="removeSelect(index)"
        />
      </div>
    </div>
    <!--    <div>当前选择：{{ state.selectObj }}</div>-->
    <!--    <div>所有选择：{{ state.selectList }}</div>-->
  </a-card>
</template>

<style lang="less" scoped>
.select-bg {
  width: 120px;
  background: #eff3f8;
  border: 3px solid #fff;
}

.ant-input {
  border: none;
}

.jutime-picker {
  height: 40px;
  line-height: 30px;
  border: none;
}

.jsearch-icon {
  width: 40px;
  line-height: 40px;
  text-align: center;
  border-left: 1px solid #d9d9d9;
}

.jsearch-selects {
  display: flex;
  margin-top: 8px;

  .select-item {
    height: 30px;
    padding: 0 8px;
    margin-right: 8px;
    font-size: 12px;
    line-height: 30px;
    border: 1px solid #d9d9d9;
    border-radius: 15px;

    span {
      margin-right: 5px;

      &:nth-child(1) {
        color: rgb(0 0 0 / 45%);
      }

      &:nth-child(2) {
        margin-right: 8px;
      }
    }
  }
}
</style>
